package zhibi.plugin.image.filter;

import zhibi.plugin.image.core.ImageHandler;
import zhibi.plugin.image.util.ImageUtil;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * Created by 执笔 on 2016/12/29.
 * 图片过滤器  自动处理图片
 *
 * 参数 ： w:宽度  整数
 *         h:高度  整数
 *         r:旋转角度
 *         q:图片质量  0到1
 *         s:比例   0到1  此时宽度高度无效
 *         t:类型    down 下载   view  展示   info 图片信息
 */
public class ImageFilter implements Filter {

    private String contextPath;

    public void init(FilterConfig filterConfig) throws ServletException {
        contextPath = filterConfig.getServletContext().getContextPath();
    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String target;
        if (null == contextPath || contextPath.equals("/")) {
            target = request.getRequestURI().replaceFirst(request.getContextPath(), "");
        } else {
            target = request.getRequestURI().substring(contextPath.length());
        }
        String fileName = target.substring(target.lastIndexOf("/") + 1);
        Map<String, String[]> paramMap = request.getParameterMap();
        if (ImageUtil.isImg(fileName) && !paramMap.isEmpty() && (
                paramMap.containsKey("w") || paramMap.containsKey("h")
                        || paramMap.containsKey("r"))) {
            ImageHandler  imageHandler = new ImageHandler();
            imageHandler.handler(target,request,response);
        } else {
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }

    public void destroy() {

    }
}
